package com.newworld.dmsapp2.fragment;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.activity.HouseManagePeopleListActivity;
import com.newworld.dmsapp2.activity.MainActivity;
import com.newworld.dmsapp2.activity.ServiceScheduleAccomplishActivity;
import com.newworld.dmsapp2.activity.ServiceScheduleActivity;
import com.newworld.dmsapp2.activity.ServiceScheduleUserValueActivity;
import com.newworld.dmsapp2.activity.ToDoTaskListActivity;
import com.newworld.dmsapp2.activity.designtask.AssignAndReassignTaskActivity;
import com.newworld.dmsapp2.activity.serviceapply.WritePaperActivity;
import com.newworld.dmsapp2.bean.Function;
import com.newworld.dmsapp2.bean.Task;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.fragment.adapter.MessageFragementAdapter;
import com.newworld.dmsapp2.fragment.adapter.TodoTaskListAdapter;
import com.newworld.dmsapp2.fragment.bean.Message;
import com.newworld.dmsapp2.ui.view.XListView;
import com.newworld.dmsapp2.ui.view.XListView.IXListViewListener;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.HttpUtil;
import com.newworld.dmsapp2.util.MyPreference;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.StringUtil;
import com.newworld.dmsapp2.util.Tool;
import com.pgyersdk.utils.m;

/**
 * 
 * @author long 消息界面
 */
public class MainMessageFragment extends Fragment implements IXListViewListener {
	private XListView messageLv;
	private ArrayList<Message> messageList = new ArrayList<Message>();
	private User user;
	private ProgressBar progressBar;
	private List<Function> functionList = new ArrayList<Function>();
	private ArrayList<String> functionCodeList = new ArrayList<String>();
	private String functionCode;
	private Message message = new Message();
	private String sessionId;
	private static Context context;
	private List<Message> refreshMessages = new ArrayList<Message>();
	private boolean refresh = false;
	private MessageFragementAdapter messageAdapter;
	private int page = 0;
	private boolean canClick = false;
	private String currentPage = null;
	private String Page = "0";
	
	private Handler mgeHandler = new Handler() {
		
		@SuppressWarnings("unchecked")
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case Config.HANDLE_MSG_RFESH_FAIL:
				Toast.makeText(context, (String) msg.obj,
						Toast.LENGTH_SHORT).show();
				break;
			case Config.HANDLE_MSG_SEARCH_FAIL:
				Toast.makeText(context, (String) msg.obj,
						Toast.LENGTH_SHORT).show();
				break;
			case Config.HANDLER_MSG_LOADING_SUCCESS:
				progressBar.setVisibility(View.INVISIBLE);
				refreshMessages = (List<Message>) msg.obj;
				/*System.out.println("显示的functioncode是" + functioncode + " "
						+ "本操作的areaType是" + areaType);*/
				/*tasks = user.getFunctionTasksFromUser(realfunctioncode,
						areaType);*/
				 if (refreshMessages.size() == 0) {
					 if (refresh) {
						 messageList.clear();
					 }
					 messageLv.hideFoot1();
				 	} else {
				 		if (refresh) {
				 			messageList.clear();
				 			messageList.addAll((List<Message>) msg.obj);
				 			messageLv.showFoot();
				 		} else {
				 			messageList.addAll((List<Message>) msg.obj);
				 			messageLv.showFoot();
				 		}
				 }

				if (null == refreshMessages || refreshMessages.size() == 0) {
					messageLv.hideFoot1();
				} else {
					messageLv.showFoot();
				}
				System.out.println("下面将显示获取到的列表->");
				messageAdapter = new MessageFragementAdapter(
						context, messageList);
				messageLv.setAdapter(messageAdapter);
				System.out.println("上面显示了获取到的列表->");
				if(page != 0){
					messageLv.setSelection(messageLv.getCount() - 1); 
				}
				
				messageAdapter.notifyDataSetChanged();
				onLoad();
				canClick = true;
				break;
			/*case Config.HANDLER_MSG_SEARCH_SUCCESS:
				progressBar.setVisibility(View.INVISIBLE);
				refreshMessages = (List<Message>) msg.obj;
				 if (refreshMessages.size() == 0) {
					 if (refresh) {
						 messageList.clear();
					 }
					 messageLv.hideFoot1();
				 	} else {
				 		if (refresh) {
				 			messageList.clear();
				 			messageList.addAll((List<Message>) msg.obj);
				 			messageLv.showFoot();
				 		} else {
				 			messageList.addAll((List<Message>) msg.obj);
				 			messageLv.showFoot();
				 		}
				 	}

				if (refreshMessages.size() == 0) {
					messageLv.hideFoot1();
				} else {
					messageLv.showFoot();
				}
				messageAdapter = new MessageFragementAdapter(
						context, messageList);
				messageLv.setAdapter(messageAdapter);
				messageAdapter.notifyDataSetChanged();
				if(page != 0){
					messageLv.setSelection(messageLv.getCount() - 1); 
				}
				onLoad();
				canClick = true;
				Toast.makeText(context, "查询成功",
						Toast.LENGTH_SHORT).show();
				break;*/
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_main_message, container,
				false);
		findView(view);
		Toast.makeText(getActivity(), "消息>>>>", Toast.LENGTH_SHORT);
		//if(MainActivity.INIT_FRAGMENT){
			init();
			/*Log.e("MainMessageFragment", "消息初始化");
			Toast.makeText(getActivity(), "消息初始化", Toast.LENGTH_SHORT);
		}else{
			Log.e("MainMessageFragment", "非消息初始化");
			Toast.makeText(getActivity(), "非消息初始化", Toast.LENGTH_SHORT);
		}*/
		
		return view;
	}

	private void init() {
		// TODO Auto-generated method stub
		MyPreference.getInstance(context).setRefreshState(
				true);
		context = this.getActivity();
		user = SingleSample.getInstance(context)
				.getUser();
		if (null != user) {
			if (null != user.getSessionId()
					&& !user.getSessionId().equals("")) {
				sessionId = user.getSessionId();
			}
		}
		
		functionList = user.getFunctions();
		for (Function function : functionList) {
			functionCodeList.add(function.getFunctionCode());
		}
		
		//peopleType = Tool.getPeopleType(functionCodeList);
		
		// 户主
		if (functionCodeList
				.contains(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTOFOWNER)) {
			functionCode = Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTOFOWNER;

		}// 非户主
		else if (functionCodeList
				.contains(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTOFNONOWNER)) {
			functionCode = Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTOFNONOWNER;

		}
		// 派单员
		else if (functionCodeList
				.contains(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTDISPACHER)) {
			functionCode = Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTDISPACHER;

		}// 主管
		else if (functionCodeList
				.contains(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTMANAGER)) {
			functionCode = Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTMANAGER;

		}// 维修人员
		else if (functionCodeList
				.contains(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTSEVER)) {
			functionCode = Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTSEVER;

		}// 项目经理
		else if (functionCodeList
				.contains(Config.FUNCTION_REAL_GETPMPROGRESSLIST)) {
			functionCode = Config.FUNCTION_REAL_GETPMPROGRESSLIST;

		}
	
		messageLv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				if(canClick && Tool.isNetworkAvailable(context)){
					Intent i = null;
					Bundle b = new Bundle();
					message = messageList.get(position-1);
					String peopleType = Tool.getPeopleType(functionCodeList);
					String messageType = message.getMessageType_typeCode();
					
					// 业主消息----->服务人员已接单
					if (message.getMessageType_typeCode()
							.equals(Config.RECEIVE_ORDER_MESSAGE)) {
						
						b.putString(Config.PEOPLETYPE, peopleType);
						
					
						b.putString(Config.STATUS_TYPE_CODE,
								Config.TYPECODE_SERVE);
						if(peopleType.equals(Config.DISPATCHER)//派单员
								||peopleType.equals(Config.DEPART_DISPATCHER)//部门派单员
								){
							b.putString(Config.FUNCTIONCODE, Config.FUNCTION_REAL_MYAPPLY);
							b.putString(Config.TASKSTATE, Config.TASKSTATE_DISTRIBUTED);
							i = new Intent(getActivity(), AssignAndReassignTaskActivity.class);
						}else if(peopleType.equals(Config.DEPART_MANAGER)){//项目经理
							b.putString(Config.FUNCTIONCODE, Config.FUNCTION_REAL_MYAPPLY);
							b.putString(Config.TASKSTATE, Config.TASKSTATE_DISTRIBUTED);
							i = new Intent(getActivity(), ServiceScheduleActivity.class);
						}else if(peopleType.equals(Config.SERVER)){//服务人员
							b.putString(Config.FUNCTIONCODE, Config.FUNCTION_REAL_MYAPPLY);
							b.putString(Config.TASKSTATE, Config.TASKSTATE_TODO);
							i = new Intent(getActivity(), ServiceScheduleActivity.class);
						}else{//业主
							b.putString(Config.FUNCTIONCODE, functionCode);
							b.putString(Config.TASKSTATE, Config.TASKSTATE_DISTRIBUTE);
							i = new Intent(getActivity(), ServiceScheduleActivity.class);
						}
					} // 业主消息----->维修完成，去评价（此时，只要是该角色自己提的单，都是业主身份评价）
					else if (message.getMessageType_typeCode()
							.equals(Config.EVALUATE_MESSAGE)) {
						b.putString(Config.PEOPLETYPE, peopleType);
						b.putString(Config.FUNCTIONCODE, functionCode);
						// 户主和非户主的维修进度
						if (functionCode
								.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTOFOWNER)
								|| functionCode
										.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTOFNONOWNER)
								|| functionCode
										.equals(Config.FUNCTION_REAL_GETOUTDOORPROGRESSLISTOFOWNER)
								|| functionCode
										.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTMANAGER)
								|| functionCode
										.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTDISPACHER)
								|| functionCode
										.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTSEVER)) {
							b.putString(Config.TASKSTATE, Config.TASKSTATE_DONE);
						}else{
							b.putString(Config.TASKSTATE, Config.TASKSTATE_EVALUATE);
							b.putString(Config.AREATYPE, Config.AREACODE_OUTDOOR);
						}
						
						if(peopleType.equals(Config.DISPATCHER)//派单员
								||peopleType.equals(Config.DEPART_DISPATCHER)//部门派单员
								){
							b.putString(Config.FUNCTIONCODE, Config.FUNCTION_REAL_MYAPPLY);
						}else if(peopleType.equals(Config.DEPART_MANAGER)){//项目经理
							b.putString(Config.FUNCTIONCODE, Config.FUNCTION_REAL_MYAPPLY);
						}else if(peopleType.equals(Config.SERVER)){//服务人员
							b.putString(Config.FUNCTIONCODE, Config.FUNCTION_REAL_MYAPPLY);
						}else{//业主
							b.putString(Config.FUNCTIONCODE, functionCode);
						}
						
						b.putString(Config.STATUS_TYPE_CODE,
								Config.TYPECODE_EVALUATE);
						i = new Intent(getActivity(),
								ServiceScheduleAccomplishActivity.class);

					} 		// 派单员消息----->业主提单
					else if (message.getMessageType_typeCode()
							.equals(Config.REPAIR_APPLY_MESSAGE)) {
						// 派单员
						b.putString(Config.PEOPLETYPE, Config.DISPATCHER);
						b.putString(Config.FUNCTIONCODE,
								Config.FUNCTION_REAL_GETDISPATCHTASKLIST);
						b.putString(Config.TASKSTATE,
								Config.TASKSTATE_NOTDISTRIBUTE);
						i = new Intent(getActivity(),
								AssignAndReassignTaskActivity.class);

					}// 派单员消息----->业主催单（一级派单流程）
					else if (message.getMessageType_typeCode().equals(Config.REMIND_MESSAGE_FOR_DISPATCHER)) {
						// 派单员
						b.putString(Config.PEOPLETYPE, Config.DISPATCHER);
						b.putString(Config.FUNCTIONCODE,
								Config.FUNCTION_REAL_GETREDISPATCHTASKLIST);
						b.putString(Config.TASKSTATE, Config.TASKSTATE_BEASKED);
						i = new Intent(getActivity(), AssignAndReassignTaskActivity.class);
					}				
					// 派单员消息----->超时督办
					else if (message.getMessageType_typeCode()
							.equals(Config.SUPERVISE_MESSAGE)) {
						// 派单员
						b.putString(Config.PEOPLETYPE, Config.DISPATCHER);
						b.putString(Config.FUNCTIONCODE, functionCode);
						b.putString(Config.TASKSTATE, Config.TASKSTATE_DUBAN);
						i = new Intent(getActivity(),
								AssignAndReassignTaskActivity.class);

					}// 派单员消息----->申请改派
					else if (message.getMessageType_typeCode()
							.equals(Config.MANAGER_REDISPATCH_MESSAGE)) {
						// 派单员
						b.putString(Config.PEOPLETYPE, Config.DISPATCHER);
						b.putString(Config.FUNCTIONCODE, functionCode);
						b.putString(Config.TASKSTATE, Config.TASKSTATE_APPLYCHANGE);
						i = new Intent(getActivity(),
								AssignAndReassignTaskActivity.class);

					}// 派单员消息----->回访
					else if (message.getMessageType_typeCode()
							.equals(Config.REVISIT_MESSAGE)) {
						// 派单员
						b.putString(Config.PEOPLETYPE, Config.DISPATCHER);
						b.putString(Config.FUNCTIONCODE, functionCode);
						b.putString(Config.TASKSTATE, Config.TASKSTATE_REVISIT);
						b.putString(Config.STATUS_TYPE_CODE,
								Config.TYPECODE_REVISIT);
						i = new Intent(getActivity(),
								ServiceScheduleAccomplishActivity.class);

					}
					// 主管消息----->已派单
					else if (message.getMessageType_typeCode()
							.equals(Config.SERVE_MESSAGE_FOR_MANAGER)) {//11111111111111111111111111111111111111111111一级流程，派单员派单怎么是这个？
						// 主管
						b.putString(Config.PEOPLETYPE, Config.DEPART_DISPATCHER);
						b.putString(Config.FUNCTIONCODE,
								Config.FUNCTION_REAL_GETMANAGERDISPATCHTASKLIST);
						b.putString(Config.TASKSTATE,
								Config.TASKSTATE_NOTDISTRIBUTE);
						i = new Intent(getActivity(),
								AssignAndReassignTaskActivity.class);

					}// 主管消息----->业主催单
					else if (message.getMessageType_typeCode()
							.equals(Config.REMIND_MESSAGE_FOR_MANAGER)) {
						// 主管
						b.putString(Config.PEOPLETYPE, Config.DEPART_DISPATCHER);
						b.putString(Config.FUNCTIONCODE,
								Config.FUNCTION_REAL_GETMANAGERREDISPATCHTASKLIST);
						b.putString(Config.TASKSTATE, Config.TASKSTATE_BEASKED);
						i = new Intent(getActivity(),
								AssignAndReassignTaskActivity.class);

					}// 主管消息----->已被改派
					else if (message.getMessageType_typeCode()
							.equals(Config.SERVE_ONLY_SEE_MESSAGE)) {
						Toast.makeText(context, "任务已被改派",
								Toast.LENGTH_SHORT).show();
          			new Thread(readMessageRun).start();
          			  message.setMessageStatusType(Config.MESSAGE_STATUS_READED);

					}// 主管消息----->申请改派
					else if (message.getMessageType_typeCode()
							.equals(Config.SERVER_REDISPATCH_MESSAGE)) {
						// 主管
						b.putString(Config.PEOPLETYPE, Config.DEPART_DISPATCHER);
						b.putString(Config.FUNCTIONCODE,
								Config.FUNCTION_REAL_GETMANAGERREDISPATCHTASKLIST);
						b.putString(Config.TASKSTATE, Config.TASKSTATE_APPLYCHANGE);
						i = new Intent(getActivity(),
								AssignAndReassignTaskActivity.class);

					}// 服务人员消息----->已派单
					else if (message.getMessageType_typeCode()
							.equals(Config.SERVE_MESSAGE_FOR_SERVER)) {
						// 服务人员
						b.putString(Config.PEOPLETYPE, Config.SERVER);
						
						List<Task> localTasks = DataSupport.where(
								"repairId = ? and user_id = ?",
								message.getBusinessId(),
								String.valueOf(user.getId())).find(Task.class);
						if (localTasks.size() > 0) {
							Task localTask = localTasks.get(0);
							b.putString(Config.TASKSTATE, localTask.getTaskState());
							b.putString(Config.STATUS_TYPE_CODE,
									localTask.getStatusType_typeCode());
							if (localTask.getTaskState().equals(
									Config.TASKSTATE_TOPOST)) {
								b.putString(Config.FUNCTIONCODE,
										Config.FUNCTION_REAL_GETREPAIRTASKLIST);
								i = new Intent(getActivity(),
										ServiceScheduleAccomplishActivity.class);
							} else {
								b.putString(Config.FUNCTIONCODE,
										Config.FUNCTION_REAL_GETREPAIRTASKLIST);
								i = new Intent(getActivity(),
										ServiceScheduleActivity.class);
							}
						} else {
							b.putString(Config.FUNCTIONCODE,
									Config.FUNCTION_REAL_GETREPAIRTASKLIST);
							b.putString(Config.TASKSTATE,
									Config.TASKSTATE_TORECEIVEORDER);
							b.putString(Config.STATUS_TYPE_CODE,
									Config.TYPECODE_RECEIVEORDER);
							b.putString(Config.PEOPLETYPE, Config.SERVER);
							i = new Intent(getActivity(),
									ServiceScheduleActivity.class);
						}

					}// 服务人员消息----->业主催单
					else if (message.getMessageType_typeCode()
							.equals(Config.REMIND_MESSAGE_FOR_SERVER)) {
						// 服务人员
						b.putString(Config.PEOPLETYPE, Config.SERVER);
						b.putString(Config.TASKSTATE, Config.TASKSTATE_BEASKED);
						b.putString(Config.STATUS_TYPE_CODE,
								Config.TYPECODE_SERVE);
						b.putString(Config.FUNCTIONCODE,
								Config.FUNCTION_REAL_GETREPAIRTASKLIST);
						i = new Intent(getActivity(),
								ServiceScheduleActivity.class);
					}
					// 房屋关联申请
					else if (message.getMessageType_typeCode()
							.equals(Config.WAIT_RELATE_MESSAGE)) {
						b.putString("houseUserId", message.getBusinessId());
						i = new Intent(getActivity(),
								HouseManagePeopleListActivity.class);

					}// 已获得户主同意\未获得户主同意
					else if (message.getMessageType_typeCode()
							.equals(Config.RELATE_ONLY_MESSAGE)) {

					}// 系统消息
					else if (message.getMessageType_typeCode()
							.equals(Config.SYSTEM_MESSAGE)) {

					}
					/*b.putString(Config.HOUSEID, message
							.getBusinessId());*/
					if(null!=message.getHouseId()&&message.getHouseId().equals("")){
						System.out.println("message--?"+message.getHouseId());
					}
					b.putString(Config.HOUSEID, message.getHouseId());
					b.putString(Config.REPAIRID, message.getBusinessId());
					b.putString(Config.HOUSEFULLNAME, message.getTitle());
					
					if (i != null) {
						new Thread(readMessageRun).start();
						i.putExtras(b);
						startActivity(i);
					}
				} else {
					Toast.makeText(context, "请检查网络连接！！",
							Toast.LENGTH_SHORT).show();
				}
				

			}
		});

	}

	// 获取消息请求
	@SuppressWarnings("unused")
	private void getMessage( final String Page1) {
		// TODO Auto-generated method stub
		if(Tool.isNetworkAvailable(context)){
			try {
				Page = Page1;
				String url = "";
				String message1 = "";
				if (null != user
						.getFunctionlistFromUser(Config.FUNCTION_PERSONNAL_MESSAGE)
						&& null != user.getFunctionlistFromUser(
								Config.FUNCTION_PERSONNAL_MESSAGE).get(
								0)) {
					url = Config.SERVER_URL
							+ user.getFunctionlistFromUser(
									Config.FUNCTION_PERSONNAL_MESSAGE)
									.get(0).getFunctionUrl();
					// 注册请求
					Map<String, String> map = new HashMap<String, String>();
					List<Message> getmessages = new ArrayList<Message>();
					map.put("functionCode",
							Config.FUNCTION_PERSONNAL_MESSAGE);
					map.put("pageNum",Page);
					String result = HttpUtil.postRequestSe(url, map,
							sessionId);
					Log.e("获取消息列表result", result);
					JSONObject jsonObj = new JSONObject(result);
					if (jsonObj.getString("flag")
							.equals("success")) {
						String rows = jsonObj.getString("rows");
						String total = jsonObj.getString("total");
						if (total.equals("0")) {
							getmessages = new ArrayList<Message>();
							mgeHandler.obtainMessage(Config.HANDLER_MSG_LOADING_SUCCESS,
									getmessages).sendToTarget();
						} else {
							if (!rows.equals("")) {
								Type type = new TypeToken<List<Message>>() {
								}.getType();
								Gson gson = new Gson();
								getmessages = gson.fromJson(rows, type);
								int count = 0;
								for (Message message : getmessages) {
									if (message.getAreaDetail() != null) {
										message.setTitle(message
												.getProjectName()
												+ message
														.getAreaDetail());
									}
									if(!StringUtil.isStringEqual(message.getMessageStatusType(), 
											Config.MESSAGE_STATUS_READED))
										count++;
								}
								//MainActivity.unreadnum = count;
								
								List<Message> changemessages = new ArrayList<Message>();
								// 先新建一个tts列表，无论这个任务是否存在，都加入进去，减少出错。
								if (null != getmessages) {

									for (Message message : getmessages) {
										//System.out.println("messageStatusType是" + messageList.get(index));
										changemessages.add(message);
									}
								} else {
									mgeHandler.obtainMessage(Config.HANDLE_MSG_RFESH_FAIL, "获取消息出错")
											.sendToTarget();
								}
								mgeHandler.obtainMessage(Config.HANDLER_MSG_LOADING_SUCCESS,
										changemessages).sendToTarget();
								
							} else {
								getmessages = new ArrayList<Message>();
							}
						}

					}
					message1 = jsonObj.getString("message");
					mgeHandler.obtainMessage(Config.HANDLE_MSG_RFESH_FAIL, message1)
						.sendToTarget();
				} else {
					message1 = "无法获取消息地址";
					mgeHandler.obtainMessage(Config.HANDLE_MSG_RFESH_FAIL, message1)
					.sendToTarget();
				}

			} catch (Exception e) {
				e.printStackTrace();
				//message1 = "获取消息失败";
			}

		
		}else{
			mgeHandler.obtainMessage(Config.HANDLE_MSG_RFESH_FAIL, "请检查网络连接！")
					.sendToTarget();
		}
		/*new AsyncTask<Void, Void, Void>() {
			private String message;
			@Override
			protected void onPreExecute() {
				if (Tool.isNetworkAvailable(getActivity())) {
					progressBar.setVisibility(View.VISIBLE);
				} else {
					Toast.makeText(getActivity(), "请检查网络连接！",
							Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			protected Void doInBackground(Void... params) {
				if(null != getActivity()){
					if (Tool.isNetworkAvailable(getActivity())) {
						try {
							Page = Page1;
							String url = "";
							if (null != user
									.getFunctionlistFromUser(Config.FUNCTION_PERSONNAL_MESSAGE)
									&& null != user.getFunctionlistFromUser(
											Config.FUNCTION_PERSONNAL_MESSAGE).get(
											0)) {
								url = Config.SERVER_URL
										+ user.getFunctionlistFromUser(
												Config.FUNCTION_PERSONNAL_MESSAGE)
												.get(0).getFunctionUrl();
								// 注册请求
								Map<String, String> map = new HashMap<String, String>();
								List<Message> getmessages = new ArrayList<Message>();
								map.put("functionCode",
										Config.FUNCTION_PERSONNAL_MESSAGE);
								map.put("pageNum",Page);
								String result = HttpUtil.postRequestSe(url, map,
										sessionId);
								Log.e("获取消息列表result", result);
								JSONObject jsonObj = new JSONObject(result);
								if (jsonObj.getString("flag")
										.equals("success")) {
									String rows = jsonObj.getString("rows");
									String total = jsonObj.getString("total");
									if (total.equals("0")) {
										getmessages = new ArrayList<Message>();
									} else {
										if (!rows.equals("")) {
											Type type = new TypeToken<List<Message>>() {
											}.getType();
											Gson gson = new Gson();
											getmessages = gson.fromJson(rows, type);
											int count = 0;
											for (Message message : getmessages) {
												if (message.getAreaDetail() != null) {
													message.setTitle(message
															.getProjectName()
															+ message
																	.getAreaDetail());
												}
												if(!StringUtil.isStringEqual(message.getMessageStatusType(), 
														Config.MESSAGE_STATUS_READED))
													count++;
											}
											MainActivity.unreadnum = count;
											
											List<Message> changemessages = new ArrayList<Message>();
											// 先新建一个tts列表，无论这个任务是否存在，都加入进去，减少出错。
											if (null != getmessages) {

												for (Message message : getmessages) {
													//System.out.println("messageStatusType是" + messageList.get(index));
													changemessages.add(message);
												}
											} else {
												mgeHandler.obtainMessage(Config.HANDLE_MSG_RFESH_FAIL, "获取消息出错")
														.sendToTarget();
											}
											mgeHandler.obtainMessage(Config.HANDLER_MSG_LOADING_SUCCESS,
													changemessages).sendToTarget();
											
										} else {
											getmessages = new ArrayList<Message>();
										}
									}

								}
								message = jsonObj.getString("message");
							} else {
								message = "无法获取消息地址";
							}

						} catch (Exception e) {
							e.printStackTrace();
							message = "获取消息失败";
						}

					}
				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				if(null != message){
					if(message.equals(null)&&!message.equals(" ")){
						Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT)
						.show();
					}
					progressBar.setVisibility(View.INVISIBLE);
					if (null != messageList && !messageList.isEmpty()) {
						messageAdapter = new MessageFragementAdapter(
								getActivity(), messageList);
						messageLv.setAdapter(messageAdapter);
					} else {
						messageList = new ArrayList<Message>();
						messageAdapter = new MessageFragementAdapter(
								getActivity(), messageList);
						messageLv.setAdapter(messageAdapter);
					}
					onLoad();
				}
			}
		}.execute(null, null, null);*/
	}
	
	// 获取未读消息数目请求
		@SuppressWarnings("unused")
		private void getUnreadMessageNum() {
			// TODO Auto-generated method stub
			if(Tool.isNetworkAvailable(context)){
				try {
					String url = "";
					String message1 = "";
					if (null != user
							.getFunctionlistFromUser(Config.FUNCTION_PERSONNAL_MESSAGE_NUM)
							&& null != user.getFunctionlistFromUser(
									Config.FUNCTION_PERSONNAL_MESSAGE_NUM).get(
									0)) {
						url = Config.SERVER_URL
								+ user.getFunctionlistFromUser(
										Config.FUNCTION_PERSONNAL_MESSAGE_NUM)
										.get(0).getFunctionUrl();
						// 注册请求
						Map<String, String> map = new HashMap<String, String>();
						List<Message> getmessages = new ArrayList<Message>();
						map.put("functionCode",
								Config.FUNCTION_PERSONNAL_MESSAGE_NUM);
						String result = HttpUtil.postRequestSe(url, map,
								sessionId);
						Log.e("获取未读消息数目result", result);
						JSONObject jsonObj = new JSONObject(result);
						if (jsonObj.getString("flag")
								.equals("success")) {
							String rows = jsonObj.getString("rows");
							String total = jsonObj.getString("total");
							if (total.equals("0")) {
								getmessages = new ArrayList<Message>();
							} else {
								if (!rows.equals("")) {
									Type type = new TypeToken<List<Message>>() {
									}.getType();
									Gson gson = new Gson();
									getmessages = gson.fromJson(rows, type);
									int count = 0;
									/*for (Message message : getmessages) {
										if (message.getAreaDetail() != null) {
											message.setTitle(message
													.getProjectName()
													+ message
															.getAreaDetail());
										}
										if(!StringUtil.isStringEqual(message.getMessageStatusType(), 
												Config.MESSAGE_STATUS_READED))
											count++;
									}*/
									MainActivity.unreadnum = count;
									
									List<Message> changemessages = new ArrayList<Message>();
									// 先新建一个tts列表，无论这个任务是否存在，都加入进去，减少出错。
									if (null != getmessages) {

										for (Message message : getmessages) {
											//System.out.println("messageStatusType是" + messageList.get(index));
											changemessages.add(message);
										}
									} else {
										mgeHandler.obtainMessage(Config.HANDLE_MSG_RFESH_FAIL, "获取未读消息数目出错")
												.sendToTarget();
									}
									mgeHandler.obtainMessage(Config.HANDLER_MSG_LOADING_SUCCESS,
											changemessages).sendToTarget();
									
								} else {
									getmessages = new ArrayList<Message>();
								}
							}

						}
						message1 = jsonObj.getString("message");
						mgeHandler.obtainMessage(Config.HANDLE_MSG_RFESH_FAIL, message1)
							.sendToTarget();
					} else {
						message1 = "无法获取未读消息数目地址";
						mgeHandler.obtainMessage(Config.HANDLE_MSG_RFESH_FAIL, message1)
						.sendToTarget();
					}

				} catch (Exception e) {
					e.printStackTrace();
					//message1 = "获取消息失败";
				}

			
			}else{
				mgeHandler.obtainMessage(Config.HANDLE_MSG_RFESH_FAIL, "请检查网络连接！")
						.sendToTarget();
			}
		}

	
	/**
	 *读过消息，与服务器交互 
	 */
	Runnable readMessageRun = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			if (Tool.isNetworkAvailable(getActivity())) {
				try {
					String result = null;
					Map<String, String> map = new HashMap<String, String>();
					String url = "";
					
						url = Config.SERVER_URL
								+ user.getFunctionlistFromUser(
										Config.FUNCTION_READ_MESSAGE)
										.get(0).getFunctionUrl();
						map.put("functionCode",
								Config.FUNCTION_READ_MESSAGE);
					map.put("messageId", message.getMessageId());
					
					result = HttpUtil.postRequestSe(url, map, sessionId);
					Log.e("读过消息的result", result);
					
				} catch (Exception e) {
					Log.e("ServiceScheduleActivity", "json数据获取报错");
					
				}

			} else {
				Log.e("ServiceScheduleActivity", "请设置网络");
			}
		}
	};

	
	
	private void findView(View view) {
		// TODO Auto-generated method stub
		messageLv = (XListView) view.findViewById(R.id.lv_fragment_message);
		progressBar = (ProgressBar) view.findViewById(R.id.proBar_get_data);
		user = SingleSample.getInstance(getActivity()).getUser();
		
		preferences = PreferenceManager
				.getDefaultSharedPreferences(getActivity());
		messageLv.setPullLoadEnable(true);
		messageLv.setPullRefreshEnable(true);// 下拉刷新
		messageLv.setXListViewListener(this);// 给xListView设置监听 ******
		messageLv.setRefreshTime(refreshUpdatedAtValue());

	}

	@Override
	public void onRefresh() {

		new AsyncTask<Void, Void, Void>() {

			@Override
			protected void onPreExecute() {
				progressBar.setVisibility(View.VISIBLE);
			}

			@Override
			protected Void doInBackground(Void... params) {
				if (Tool.isNetworkAvailable(context)) {
					try {
						refresh = true;
						page = 0;
						Page = String.valueOf(page);
						refresh = true;
						getMessage(Page);
						//getUnreadMessageNum();
						System.out.println("page------->" + page);
						Log.e("onRefresh", page + "");
						preferences
								.edit()
								.putLong(UPDATED_AT + mId,
										System.currentTimeMillis()).commit();
					} catch (Exception e) {
						Log.e("GLTASKFragment", "onRefresh 网络连接问题");
						e.printStackTrace();
					}

				} else {
					
				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				
			}
		}.execute(null, null, null);
	
		// TODO Auto-generated method stub
		//if(MainActivity.INIT_FRAGMENT){
		
		/*	Log.e("MainMessageFragment", "消息初始化getMessage");
			Toast.makeText(getActivity(), "消息初始化getMessage", Toast.LENGTH_SHORT);
		}else{
			Log.e("MainMessageFragment", "非消息初始化getMessage");
			Toast.makeText(getActivity(), "非消息初始化getMessage", Toast.LENGTH_SHORT);
		}*/
		
	}

	/*public void onLoadMore() {
		// TODO Auto-generated method stub

	}*/
	/*@Override
	public void onLoadMore() {
		mgeHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				refresh = false;
				page++;
				Page = String.valueOf(page);
				Log.e("onloadmore", page + "");
				getMessage(Page);
				// onLoad();
			}
		}, 1000);
	}*/

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		onRefresh();
		if (messageAdapter != null) {
			messageAdapter.notifyDataSetChanged();
		}
	}

	private void onLoad() {
		messageLv.stopRefresh();
		messageLv.stopLoadMore();
		messageLv.setRefreshTime(refreshUpdatedAtValue());
	}

	/**
	 * 刷新下拉头中上次更新时间的文字描述。
	 */
	private String refreshUpdatedAtValue() {
		lastUpdateTime = preferences.getLong(UPDATED_AT + mId, -1);
		long currentTime = System.currentTimeMillis();
		long timePassed = currentTime - lastUpdateTime;
		long timeIntoFormat;
		String updateAtValue = null;
		try {
			if(null != getResources()){
				if (lastUpdateTime == -1) {
					updateAtValue = getResources().getString(R.string.not_updated_yet);
				} else if (timePassed < 0) {
					updateAtValue = getResources().getString(R.string.time_error);
				} else if (timePassed < ONE_MINUTE) {
					updateAtValue = getResources().getString(R.string.updated_just_now);
				} else if (timePassed < ONE_HOUR) {
					timeIntoFormat = timePassed / ONE_MINUTE;
					String value = timeIntoFormat + "分钟";
					updateAtValue = String.format(
							getResources().getString(R.string.updated_at), value);
				} else if (timePassed < ONE_DAY) {
					timeIntoFormat = timePassed / ONE_HOUR;
					String value = timeIntoFormat + "小时";
					updateAtValue = String.format(
							getResources().getString(R.string.updated_at), value);
				} else if (timePassed < ONE_MONTH) {
					timeIntoFormat = timePassed / ONE_DAY;
					String value = timeIntoFormat + "天";
					updateAtValue = String.format(
							getResources().getString(R.string.updated_at), value);
				} else if (timePassed < ONE_YEAR) {
					timeIntoFormat = timePassed / ONE_MONTH;
					String value = timeIntoFormat + "个月";
					updateAtValue = String.format(
							getResources().getString(R.string.updated_at), value);
				} else {
					timeIntoFormat = timePassed / ONE_YEAR;
					String value = timeIntoFormat + "年";
					updateAtValue = String.format(
							getResources().getString(R.string.updated_at), value);
				}
			}
		} catch (IllegalStateException e) {
			// TODO: handle exception
			Log.e("MainMessageFragment", "IllegalStateException");
		}
		return updateAtValue;
	}

	/**
	 * 一分钟的毫秒值，用于判断上次的更新时间
	 */
	public static final long ONE_MINUTE = 60 * 1000;

	/**
	 * 一小时的毫秒值，用于判断上次的更新时间
	 */
	public static final long ONE_HOUR = 60 * ONE_MINUTE;

	/**
	 * 一天的毫秒值，用于判断上次的更新时间
	 */
	public static final long ONE_DAY = 24 * ONE_HOUR;

	/**
	 * 一月的毫秒值，用于判断上次的更新时间
	 */
	public static final long ONE_MONTH = 30 * ONE_DAY;

	/**
	 * 一年的毫秒值，用于判断上次的更新时间
	 */
	public static final long ONE_YEAR = 12 * ONE_MONTH;

	/**
	 * 上次更新时间的字符串常量，用于作为SharedPreferences的键值
	 */
	private static final String UPDATED_AT = "updated_at";

	/**
	 * 用于存储上次更新时间
	 */
	private SharedPreferences preferences;

	/**
	 * 上次更新时间的毫秒值
	 */
	private long lastUpdateTime;
	/**
	 * 为了防止不同界面的下拉刷新在上次更新时间上互相有冲突，使用id来做区分
	 */
	private int mId = -1;

	@Override
	public void onLoadMore() {
		// TODO 自动生成的方法存根
		//Toast.makeText(context, "1111", Toast.LENGTH_SHORT).show();
		mgeHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				refresh = false;
				page++;
				Page = String.valueOf(page);
				Log.e("onloadmore", page + "");
				getMessage(Page);
				//getUnreadMessageNum();
				// onLoad();
			}
		}, 1000);
	}
}
